package com.ruoyi.aitcommon.controller;

import java.util.*;

import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.service.SQLService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.utils.JSONResult;
import com.ruoyi.aitcommon.utils.RuntimeManager;
import com.ruoyi.aitcommon.utils.SQLUtils;
import com.ruoyi.aitcommon.utils.VersionUtils;
import com.ruoyi.aitcommon.vo.RuntimeVO;

/**
 * 在SecurityConfig类中配置,跳过鉴权
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/aitcommon/dashboard")
public class AITDashboardController {
	@Autowired
	RuntimeManager runtimeManager;
	@Autowired
	SQLService sqlService;
	@Autowired
	ConfigManager configManager;
	
	/**
	 * 流程运行监控
	 * @return
	 */
	@GetMapping("/runtime")
	public JSONObject getRuntime(){
		try {
//			获取所有运行监控清单
			List<RuntimeVO> runList = runtimeManager.getRunList(-1);

//			返回结果
			return JSONResult.success(runList);
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage());
		}
	}
	
	/**
	 * AIT版本信息
	 * @return
	 */
	@GetMapping("/aitversion")
	public JSONObject getAitVersion() {
		try {
			Map<String,Object> retmap=new LinkedHashMap<String,Object>();
			retmap.put("codeVersion", VersionUtils.getCodeVersion());
			retmap.put("dbVersion", VersionUtils.getDBVersion());
			return JSONResult.success(retmap);
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage(),ex);
		}
	}
	
	/**
     * ait日志统计
     */
    @GetMapping("/aitlog")
    public JSONObject getAitLogStats()
    {
        try {
			final Object sql = configManager.getContextByParm("sysflow.AITState_KB");
			final List<Map<String, Object>> retlist = SQLUtils.execQuery(sql.toString());
			return JSONResult.success(retlist);
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }
    
    /**
     * 定时任务信息
     */
    @GetMapping("/job")
    public JSONObject getJobStats()
    {
    	Map<String,Object> retmap=new LinkedHashMap<String,Object>();
    	Map<String,String> sqlmap=new HashMap<String,String>(){
			private static final long serialVersionUID = 1L;
		{
//			任务总数
    		put("jobtotal","select count(1) cnt from qrtz_triggers");
//    		任务活跃数
    		put("jobtotal1","select count(1) cnt from qrtz_triggers where trigger_state!='PAUSED'");
//    		昨日执行次数
    		put("jobRun","select count(1) cnt from sys_job_log where date(create_time)=date(DATE_ADD(now(),INTERVAL -1 DAY));");
//    		昨日执行平均(小时)
    		put("jobRun1","select round(count(1)/24,2) cnt from sys_job_log where date(create_time)=date(DATE_ADD(now(),INTERVAL -1 DAY));");
//    		今日执行次数
    		put("todayRun","select count(1) cnt from sys_job_log where date(create_time)=date(now());");
//    		今日执行平均(小时)
    		put("todayRun1","select round(count(1)/24,2) cnt from sys_job_log where date(create_time)=date(now());");
    	}};
        try {
        	for(String key:sqlmap.keySet()) {
        		Object ret=SQLUtils.execQueryOne(sqlmap.get(key), "cnt");
        		retmap.put(key, ret);
        	}
        	return JSONResult.success(retmap);
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }

	/**
	 * MYSQL数据库信息
	 */
	@GetMapping("/dbinfo")
	public JSONObject getDBInfo()
	{
		List<Map<String,Object>> retlist=new ArrayList<>();
		String sql;
		List<Map<String, Object>> list;
		try{
			//获取MYSQL缓存相关信息
			sql="show variables like 'innodb_buffer_pool%'";
			list = SQLUtils.execQuery(sql);
			for (Map<String, Object> item : list) {
				String key=item.get("Variable_name").toString();
				Object val=item.get("Value");
				if(key.equals("innodb_buffer_pool_chunk_size")
						||key.equals("innodb_buffer_pool_instances")
						||key.equals("innodb_buffer_pool_size")){
					String showVal="";
					if(key.equals("innodb_buffer_pool_chunk_size")
					||key.equals("innodb_buffer_pool_size")){
						showVal=Long.parseLong(val.toString())/1024/1024+"M";
					}else{
						showVal=val.toString();
					}
					Map retmap=new LinkedHashMap();
					retmap.put("name",key);
					retmap.put("val",showVal);
					retmap.put("warn",false);
					if(key.equals("innodb_buffer_pool_size"))
						if(Long.parseLong(val.toString())<1024*1024*1024){
							retmap.put("warn",true);
						}
					retlist.add(retmap);
				}
			}
			//获取MYSQL地址
			sql="select @@basedir dir";
			list = SQLUtils.execQuery(sql);
			if(list!=null&&list.size()>0){
				Map retmap=new LinkedHashMap();
				final Map<String, Object> map1 = list.get(0);
				retmap.put("name","base_dir");
				retmap.put("val",map1.get("dir"));
				retmap.put("warn",false);
				retlist.add(retmap);
			}
			//获取MYSQL Data地址
			sql="select @@datadir dir;";
			list = SQLUtils.execQuery(sql);
			if(list!=null&&list.size()>0){
				Map retmap=new LinkedHashMap();
				final Map<String, Object> map1 = list.get(0);
				retmap.put("name","data_dir");
				retmap.put("val",map1.get("dir"));
				retmap.put("warn",false);
				retlist.add(retmap);
			}

			return JSONResult.success(retlist);
		}catch (Exception ex){
			return JSONResult.error(ex.getMessage());
		}
	}
}
